package org.util;

import org.pojo.TestFile;
import org.pojo.TestVO;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Field;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author huangshen
 * @version 0.0.3
 * @description ObjectUtil
 * @since 2022/1/24 14:23
 */
public class ObjectUtils {

    public TestVO testVO() {
        List<TestFile> testFiles = new LinkedList<>();
        TestFile testFile = new TestFile();
        testFile.setFileName("11");
        testFiles.add(testFile);

        String message = "1";

        return new TestVO(message, testFiles);
    }

    public static Map<Integer, String> sortMapByKey(Map<Integer, String> map) {
        if (CollectionUtils.isEmpty(map)) {
            return Collections.emptyMap();
        }
        //treeMap适用于按自然顺序或自定义顺序遍历键(key)
        Map<Integer, String> treeMap = new TreeMap<>(new MapKeyComparator());
        treeMap.putAll(map);
        return treeMap;
    }

    public static List<Map<String, Object>> transformBeanToMap(List<?> beanList)
            throws IllegalArgumentException, IllegalAccessException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (Object object : beanList) {
            Map<String, Object> map = new HashMap<>();
            for(Field field : object.getClass().getDeclaredFields()){
                field.setAccessible(true);
                map.put(field.getName(), field.get(object));
            }
            list.add(map);
        }
        return list;
    }
}
